package com.utils.testUpload.controller;

import com.utils.common.ResponseEnum;
import com.utils.common.ServerResponse;
import com.utils.testUpload.service.TestUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;


@RestController
@RequestMapping(value="/TestUploadController")
public class TestUploadController {

    private static Logger logger = LoggerFactory.getLogger(TestUploadController.class);
    private final String FILEPATH = "/data/apps/uploadFile";

    @Autowired
    private TestUploadService uploadService;

    @PostMapping("/setUploadFile")
    public ServerResponse setUploadFile(HttpServletRequest request) throws IOException {

        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("voice");
        if(CollectionUtils.isEmpty(files)){
            logger.info("无法获取到文件");
        }
        MultipartFile multipartFile = files.get(0);
        File baseFile = new File(FILEPATH);
        String ss = File.separator;
        String filePath = baseFile.getPath();
        File pfile = new File(filePath);
        if (!pfile.exists()) {
            pfile.mkdirs();
        }else{
            uploadService.deleteFile(pfile);
            pfile.mkdirs();
        }
        filePath = filePath + ss + multipartFile.getOriginalFilename();
        File file = new File(filePath);
        multipartFile.transferTo(file);
        return ServerResponse.getInstance().responseEnum(ResponseEnum.UPLOAD_SUCCESS);
    }

    @GetMapping(value = "/downloadLocal/{fileName}")
    public void downloadLocal(@PathVariable String fileName, HttpServletResponse response) throws FileNotFoundException {

        File baseFile = new File(FILEPATH);
        String ss = File.separator;
        // 读到流中
        InputStream inStream = new FileInputStream(baseFile.getPath() + ss + fileName);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
